using System.Collections;
using System.Collections.Generic;
using QFramework;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using System;
using ByteCloudGameSdk;
using UnityEngine.XR;


// 学生管理；包括 新增学生，学生答题，管理学生列表，监听倒计时结束事件，做本题结算逻辑
public class StudentManager : MonoBehaviour
{

    public Transform canvas;
    private List<GameObject> studentsNodes; // 学生节点列表
    public List<GameObject> studentPrefab; // 学生预制体资源引用

    public List<GameObject> studentPrefabChild; // 学生预制体资源引用_子节点，用来升级的
    public List<GameObject> studentAreaList; // 学生预制体资源引用

    public List<GameObject> DalaoAnima;//大佬的进程动画特效

    public GameObject JinJiAnim;//大佬的进程动画特效
    public int gameMode = 1; // 个人赛事1，班级赛是2

    public float studentWalkSpeed = 500f; // 学生行走速度 (单位/秒)
    public float minWalkDuration = 0.1f; // 最短行走动画时长
    public float spineAnimNominalSpeed = 20f; // Spine行走动画在TimeScale=1时对应的自然行走速度

    // 新增：随机行走相关参数
    private float studentWanderSpeed = 50f; 
    private float wanderRadius = 30f;       
    private float minWanderWaitTime = 2f;   
     private float maxWanderWaitTime = 5f;   

     private int lowStudentCountThreshold = 10; // 学生数量少于此值时，在中心区域生成
    private float centralSpawnAreaRadius = 200f; // 中心生成区域的半径

    private List<Vector3> pendingTargetPositions = new List<Vector3>(); // 新增：追踪正在前往的目标位置

    void Awake()
    {
        //监听倒计时结束，做本题结算逻辑
        StringEventSystem.Global.Register(EventID.TimeOver, () =>
            {
                HandleSingleSettlement();
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
         StringEventSystem.Global.Register(EventID.SingleModeJifenOver, (List<GameObject> studentsNodes) =>
            {
                SortByJifen(studentsNodes);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        StringEventSystem.Global.Register(EventID.ClassJifenOver, (List<GameObject> studentsNodes) =>
            {
                SortByJifen(studentsNodes);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        //个人正确
        StringEventSystem.Global.Register(EventID.GiftPersonalRight, (GameObject studentsNode) =>
            {
                PersonalRight(studentsNode);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        //班级积分翻倍
        StringEventSystem.Global.Register(EventID.GiftClassJiFenFanBei, (GameObject studentsNode) =>
            {
                ClassJiFenFanBei(studentsNode);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        //班级全班正确
        StringEventSystem.Global.Register(EventID.GiftClassAllRight, (GameObject studentsNode) =>
            {
                ClassAllRight(studentsNode);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
         //班级减少错误
        StringEventSystem.Global.Register(EventID.GiftClassReduceWrong, (GameObject studentsNode) =>
            {
                ClassReduceWrong(studentsNode);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        StringEventSystem.Global.Register(EventID.SocketUpdateUserLevel, (String studentId) =>
            {
                HandleUpdateLevel(studentId);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
    }
    void Start()
    {
        studentsNodes = new List<GameObject>();
    }

    // 添加学生
    public GameObject AddStudent(
        string studentId,
        string avatar,
        string nickname,
        StudentLevel level = StudentLevel.YouErYuan,
        GameObject studentArea = null,
        int classType = 0, //0个人赛 1代表班级赛A  2代表班级赛B
        int liansheng = 0
        )
    {
        GameObject studentPrefabInstance = level switch
        {
            StudentLevel.XiaoXueSheng => CreateStudentPrefab(studentPrefab[1], avatar, nickname),
            StudentLevel.ChuZhongSheng => CreateStudentPrefab(studentPrefab[2], avatar, nickname),
            StudentLevel.GaoZhongSheng => CreateStudentPrefab(studentPrefab[3], avatar, nickname),
            StudentLevel.DaXueSheng => CreateStudentPrefab(studentPrefab[4], avatar, nickname),
            StudentLevel.BoShiSheng => CreateStudentPrefab(studentPrefab[5],
                                avatar,
                                nickname),
            StudentLevel.YouErYuan => CreateStudentPrefab(studentPrefab[0], avatar, nickname),
            _ => CreateStudentPrefab(studentPrefab[0], avatar, nickname),
        };
        // studentsNodes.Add(studentPrefabInstance); // 这行将移到确定目标位置之后
       
        // 赋值信息到对应的组件中
        studentPrefabInstance.GetComponentInChildren<Student>().InitStudentInfo(studentId, avatar, nickname, level,classType) ;
        studentPrefabInstance.GetComponentInChildren<Student>().setLiansheng(liansheng); // 设置连胜
        // studentPrefabInstance.transform.SetParent(studentArea.transform, false); // 这行也将移到确定目标位置之后

        // 新逻辑：确定目标位置
        Vector3 targetWorldPosition;
        if (studentArea == null)
        {
            Debug.LogError("studentArea is null. Cannot determine target position for student: " + nickname);
            targetWorldPosition = Vector3.zero; 
        }
        else
        {
            Collider areaCollider = studentArea.GetComponent<Collider>();
            Bounds spawnBoundsToUse;

            if (areaCollider == null) 
            {
                Debug.LogError("StudentArea does not have a Collider component. Using studentArea's transform position as center for a default large spawn area.", studentArea);
                Vector3 fallbackCenter = studentArea.transform.position;
                spawnBoundsToUse = new Bounds(new Vector3(fallbackCenter.x, fallbackCenter.y, 0f), new Vector3(1000f, 1000f, 1f)); // 定义一个大的回退区域
            } 
            else 
            {
                if (studentsNodes.Count < lowStudentCountThreshold)
                {
                    // 学生数量少，使用中心的小区域
                    Vector3 mainAreaCenter = areaCollider.bounds.center;
                    Vector3 centralSpawnPoint = new Vector3(mainAreaCenter.x, mainAreaCenter.y, 0f); // 确保Z轴为0，与FindSparsePosition协调
                    spawnBoundsToUse = new Bounds(centralSpawnPoint, new Vector3(centralSpawnAreaRadius * 2, centralSpawnAreaRadius * 2, 1f));
                    Debug.Log($"Spawning in central area. Student count: {studentsNodes.Count} {spawnBoundsToUse.size}");
                }
                else
                {
                    // 学生数量多，使用完整区域
                    spawnBoundsToUse = areaCollider.bounds;
                    Debug.Log($"Spawning in full area. Student count: {studentsNodes.Count} {spawnBoundsToUse.size}");
                }
            }
            targetWorldPosition = FindSparsePosition(spawnBoundsToUse, studentsNodes, pendingTargetPositions); 
        }
        
        pendingTargetPositions.Add(targetWorldPosition); // 将新确定的目标位置加入待办列表

        // 在确定了目标位置之后，再设置父节点和添加到列表
        if (studentArea != null) { // 避免 studentArea 为 null 时出错
            studentPrefabInstance.transform.SetParent(studentArea.transform, false);
        }
        studentsNodes.Add(studentPrefabInstance); // 现在将新学生添加到列表中

        // 设置 prefab 实例的初始位置和动画
        studentPrefabInstance.transform.localPosition = new Vector3(632f, 448f, 0f); // 初始局部位置
        studentPrefabInstance.transform.localScale = Vector3.zero; // 初始缩放 (保持原有逻辑)

        Student studentComponent = studentPrefabInstance.GetComponentInChildren<Student>();

        // 计算Spine动画的TimeScale以匹配行走速度
        float timeScaleFactor = 1.0f;
        if (spineAnimNominalSpeed > 0.001f) // 避免除以零
        {
            timeScaleFactor = studentWalkSpeed / spineAnimNominalSpeed;
        }
        // 可以选择性地限制timeScaleFactor的范围，例如：
        // timeScaleFactor = Mathf.Clamp(timeScaleFactor, 0.1f, 5f); 

        if (studentComponent != null)
        {
            studentComponent.PlayWalkAnimation(5); // 开始行走动画并传入计算好的TimeScale
        }

        // float distance = Vector3.Distance(studentPrefabInstance.transform.localPosition, targetWorldPosition); // 原有逻辑使用localPosition，但targetWorldPosition是世界坐标
        // DOMove 的目标是世界坐标, studentPrefabInstance.transform.position 是当前的世界坐标（基于其父对象和localPosition）
        float distance = Vector3.Distance(studentPrefabInstance.transform.position, targetWorldPosition);
        
        float walkDuration = minWalkDuration; // 默认使用最小动画时长
        if (studentWalkSpeed > 0.001f) // 避免除以零或过小的速度
        {
            walkDuration = Mathf.Max(minWalkDuration, distance / studentWalkSpeed);
        }
        
        // 为了在 lambda 中使用 targetWorldPosition，捕获它
        Vector3 finalTargetPosition = targetWorldPosition; 

        Vector3 currentPosForSplitMove = studentPrefabInstance.transform.position;
        float actualDeltaX = Mathf.Abs(finalTargetPosition.x - currentPosForSplitMove.x);
        float actualDeltaY = Mathf.Abs(finalTargetPosition.y - currentPosForSplitMove.y);
        float lPathDist = actualDeltaX + actualDeltaY;

        if (lPathDist <= 0.001f) // 如果目标位置与当前位置相同 (几乎没有移动距离)
        {
            // 原始 DOMove 在这种情况下会等待 walkDuration 然后执行 OnComplete
            // 我们用一个延迟序列来模拟这个行为
            DOTween.Sequence()
                .AppendInterval(walkDuration) // 使用预先计算的 walkDuration
                .OnComplete(() =>
                {
                    if (studentComponent != null)
                    {
                        studentComponent.PlayStandAnimation(); // 到达后播放站立动画
                    }
                    pendingTargetPositions.Remove(finalTargetPosition); // 学生到达后，从待办列表中移除其目标位置
                    // 开始在该目标点附近随机行走
                    if (studentPrefabInstance != null && studentPrefabInstance.activeInHierarchy)
                    {
                        StartCoroutine(WanderAroundPointCoroutine(studentPrefabInstance, finalTargetPosition, studentComponent));
                    }
                });
        }
        else
        {
            // 按比例分配 walkDuration 给 X 和 Y 方向的移动
            float durationXSegment = walkDuration * (actualDeltaX / lPathDist);
            float durationYSegment = walkDuration * (actualDeltaY / lPathDist);

            Sequence studentMoveSequence = DOTween.Sequence();

            // X轴移动
            if (actualDeltaX > 0.001f) // 仅当X方向有实际移动时才添加
            {
                studentMoveSequence.Append(studentPrefabInstance.transform.DOMoveX(finalTargetPosition.x, durationXSegment)
                    .SetEase(Ease.Linear));
            }

            // Y轴移动
            if (actualDeltaY > 0.001f) // 仅当Y方向有实际移动时才添加
            {
                studentMoveSequence.Append(studentPrefabInstance.transform.DOMoveY(finalTargetPosition.y, durationYSegment)
                    .SetEase(Ease.Linear));
            }
            
            // 为整个序列设置 OnComplete 回调
            studentMoveSequence.OnComplete(() =>
            {
                if (studentComponent != null)
                {
                    studentComponent.PlayStandAnimation(); // 到达后播放站立动画
                }
                pendingTargetPositions.Remove(finalTargetPosition); // 学生到达后，从待办列表中移除其目标位置
                // 开始在该目标点附近随机行走
                if (studentPrefabInstance != null && studentPrefabInstance.activeInHierarchy)
                {
                    StartCoroutine(WanderAroundPointCoroutine(studentPrefabInstance, finalTargetPosition, studentComponent));
                }
            });
        }
        
        return studentPrefabInstance;
    }

    // 新增：学生在指定点附近随机行走的协程
    private IEnumerator WanderAroundPointCoroutine(GameObject studentObject, Vector3 centerPoint, Student studentComponent)
    {
        if (studentObject == null || studentComponent == null)
            yield break;

        // 确保 studentObject 初始时是站立姿态，如果之前没有 PlayStandAnimation 的话
        // studentComponent.PlayStandAnimation(); 
        // yield return new WaitForSeconds(Random.Range(minWanderWaitTime, maxWanderWaitTime)); // 初始等待一下再开始动

        while (studentObject != null && studentObject.activeInHierarchy)
        {
            // 1. 在中心点附近的指定半径内计算一个新的随机目标点
            Vector2 randomOffset = UnityEngine.Random.insideUnitCircle * wanderRadius;
            Vector3 nextWanderTarget = centerPoint + new Vector3(randomOffset.x, randomOffset.y, centerPoint.z); // 保持原始Z轴

            // 2. 计算移动参数
            float distanceToWanderTarget = Vector3.Distance(studentObject.transform.position, nextWanderTarget);
            float wanderDuration = minWalkDuration; // 使用一个基础时长
            if (studentWanderSpeed > 0.001f)
            {
                wanderDuration = Mathf.Max(minWalkDuration, distanceToWanderTarget / studentWanderSpeed);
            }

            // 3. 播放行走动画，并计算动画速率因子
            float wanderTimeScaleFactor = 1.0f;
            if (spineAnimNominalSpeed > 0.001f) 
            {
                wanderTimeScaleFactor = studentWanderSpeed / spineAnimNominalSpeed;
            }
            studentComponent.PlayWalkAnimation(wanderTimeScaleFactor);

            // 4. 使用 DOTween 移动到新的随机点
            bool moveCompleted = false;
            studentObject.transform.DOMove(nextWanderTarget, wanderDuration)
                .SetEase(Ease.Linear)
                .OnComplete(() => 
                {
                    if (studentComponent != null) // 再次检查，以防万一对象在Tween过程中被销毁
                    {
                        studentComponent.PlayStandAnimation();
                    }
                    moveCompleted = true;
                });

            // 等待当前移动完成
            yield return new WaitUntil(() => moveCompleted || studentObject == null || !studentObject.activeInHierarchy);
            
            if (studentObject == null || !studentObject.activeInHierarchy) yield break; // 如果对象没了，退出协程

            // 5. 随机等待一段时间
            float waitTime = UnityEngine.Random.Range(minWanderWaitTime, maxWanderWaitTime);
            yield return new WaitForSeconds(waitTime);
        }
    }

    //学生节点的父节点
    private GameObject CreateStudentPrefab(
        GameObject student,
        string avatar,
        string nickname)
    {
        GameObject studentPrefabInstance = Instantiate(student, Vector3.zero, Quaternion.identity) as GameObject; // 实例化预制体
        Student studentComponent = studentPrefabInstance.GetComponentInChildren<Student>();
        studentComponent.UpdateInfo(avatar, nickname,()=>{
            studentPrefabInstance.AddComponent<EnterNormalAnima>();
        });
        return studentPrefabInstance;
    }

    //学生节点的子节点
    //用在升级的时候，需要把学生节点的子节点拿出来，然后放到学生节点的父节点上
    private GameObject CreateStudentChildPrefab(
        GameObject student,
        string avatar,
        string nickname)
    {
        GameObject studentPrefabInstance = Instantiate(student, Vector3.zero, Quaternion.identity,canvas.transform) as GameObject; // 实例化预制体
        
        //修改节点的名称
        // studentPrefabInstance.name = "student";
        Student studentComponent = studentPrefabInstance.GetComponentInChildren<Student>();
        studentComponent.UpdateInfo(avatar, nickname,()=>{
            studentPrefabInstance.AddComponent<EnterNormalAnima>();
        });
        return studentPrefabInstance;
    }

    private void HandleSingleSettlement()
    {       
        if (PlayerPrefs.GetString(GameMode.Mode) == GameMode.Single){
            StringEventSystem.Global.Send(EventID.SingleJieSuanStart,studentsNodes);
        }else if(PlayerPrefs.GetString(GameMode.Mode) == GameMode.Tuandui){
           
            StringEventSystem.Global.Send(EventID.ClassJieSuanStart,studentsNodes);
        }
    }



    public void UserEnter(LiveCommentData user,int classType = 0) {
        //根据用户信息，生成学生
        GameUserData user_info = user.game_user;
        StudentLevel userLevel = user_info.level switch
        {
            0 => StudentLevel.YouErYuan,
            1 => StudentLevel.XiaoXueSheng,
            2 => StudentLevel.ChuZhongSheng,
            3 => StudentLevel.GaoZhongSheng,
            4 => StudentLevel.DaXueSheng,
            5 => StudentLevel.BoShiSheng,
            _ => StudentLevel.YouErYuan,
        };
        GameObject studentObject = null;
        if(PlayerPrefs.GetString(GameMode.Mode) == GameMode.Tuandui){
            switch (classType){
                case 1:
                studentObject = AddStudent(
                    user_info.id.ToString(), 
                    user.avatar_url, 
                    user.nickname,
                    userLevel,
                    studentAreaList[0],
                    classType,
                    user.game_user.liansheng);
                    break;
                case 2:
                studentObject = AddStudent(
                    user_info.id.ToString(), 
                    user.avatar_url, 
                    user.nickname,
                    userLevel,
                    studentAreaList[1],
                    classType,
                    user.game_user.liansheng);
                    break;
            }
        }else{
                studentObject = AddStudent(
                    user_info.id.ToString(), 
                    user.avatar_url, 
                    user.nickname,
                    userLevel,
                    studentAreaList[0],
                    0,
                    user.game_user.liansheng);
        }
        // TODO  修改大佬进场动画的地方
        if (userLevel == StudentLevel.DaXueSheng || userLevel == StudentLevel.BoShiSheng || userLevel == StudentLevel.GaoZhongSheng)
         {
             AddDalaoDialog(studentObject);
         }
       
    }
    private void SortByJifen(List<GameObject> studentsNodes){
         //然后根据每个学生答对的积分，对list进行排序
        studentsNodes.Sort((x, y) =>
        {
            return y.GetComponentInChildren<Student>().getJifen().CompareTo(x.GetComponentInChildren<Student>().getJifen());
        });
        //获取玩法模式
         if(PlayerPrefs.GetString(GameMode.Mode) == GameMode.Single){
            StringEventSystem.Global.Send(EventID.SingleJieSuanTop3,studentsNodes);
         }else{
            StringEventSystem.Global.Send(EventID.ClassJieSuanTop3,studentsNodes);
         }   
    }
    
    private void AddDalaoDialog(GameObject user){
        //初始化prefab
        if (canvas != null)
        {
            GameObject _dalaoAnima = DalaoAnima[0];
            // 在 Canvas 下实例化弹窗
            switch(user.GetComponentInChildren<Student>().level){
                case StudentLevel.BoShiSheng:
                    _dalaoAnima = DalaoAnima[0];
                    break;
                case StudentLevel.DaXueSheng:
                    _dalaoAnima = DalaoAnima[1];
                    break;
                case StudentLevel.GaoZhongSheng:
                    _dalaoAnima = DalaoAnima[2];
                    break;
                default:
                    _dalaoAnima = DalaoAnima[0];
                    break;
            }
            Dalao dalao = Instantiate(_dalaoAnima, canvas.transform).GetComponent<Dalao>();
            dalao.initialize(user);
        }
        
    }

    //TODO 升级动画
    private void UpdateLevel(GameObject student)
    {
        if(student == null || student.GetComponentInChildren<Student>() == null)
        {
            return;
        }

        Student sd = student.GetComponentInChildren<Student>();
        GameObject oldChild = sd.gameObject;
       
        
        // 不立即销毁，而是先创建新节点，然后再销毁旧节点
        StartCoroutine(NoGapUpdateLevelCoroutine(student, sd,oldChild));
    }

    private IEnumerator NoGapUpdateLevelCoroutine(GameObject student, Student sd ,GameObject oldChild)
    {
        // 确定升级后的等级和预制体索引
        int prefabIndex = 0;
        StudentLevel newLevel = sd.level;
        
        switch (sd.level)
        {
            case StudentLevel.YouErYuan:
                newLevel = StudentLevel.XiaoXueSheng;
                prefabIndex = 0;
                break;
            case StudentLevel.XiaoXueSheng:
                newLevel = StudentLevel.ChuZhongSheng;
                prefabIndex = 1;
                break;
            case StudentLevel.ChuZhongSheng:
                newLevel = StudentLevel.GaoZhongSheng;
                prefabIndex = 2;
                break;
            case StudentLevel.GaoZhongSheng:
                newLevel = StudentLevel.DaXueSheng;
                prefabIndex = 3;
                break;
            case StudentLevel.DaXueSheng:
                newLevel = StudentLevel.BoShiSheng;
                prefabIndex = 4;
                break;
            case StudentLevel.BoShiSheng:
                newLevel = StudentLevel.BoShiSheng;
                prefabIndex = 5;
                break;
        }
        
        // 先设置新的等级
        sd.level = newLevel;
        
        // 确保预制体数组索引有效
        if (prefabIndex >= 0 && prefabIndex < studentPrefabChild.Count)
        {
            GameObject prefab = studentPrefabChild[prefabIndex];
            if (prefab != null)
            {
                // 创建新节点
                GameObject newChild = CreateStudentChildPrefab(prefab, sd.getAvatarUrl(), sd.getNickname());
                
                if (newChild != null)
                {
                    // 设置新节点的父节点，但初始时隐藏它
                    newChild.transform.SetParent(student.transform);
                    //设置坐标
                    newChild.transform.localPosition = Vector3.zero;
                    
                    // 初始化信息
                    Student childStudent = newChild.GetComponent<Student>();
                    if (childStudent != null)
                    {
                        childStudent.InitStudentInfo(
                            sd.getStudentID(),
                            sd.getAvatarUrl(),
                            sd.getNickname(),
                            sd.level,
                            sd.getClassType(),
                            sd.getJifen(),
                            sd.getTotalQuestions(),
                            sd.getCorrectAnswers(),
                            sd.getBeishu(),
                            sd.getAnswer(),
                            sd.getLiansheng()
                        );
                         oldChild.SetActive(false);
                        oldChild.DestroySelf();
                    }
                   
                }
            }
        }
        
        yield return null;
    }

    // 添加到StudentManager类中
    public List<GameObject> GetAllStudents() 
    {
        return studentsNodes;
    }
    
    void HandleUpdateLevel(string  studentID){
        var studentNode = GetStudentById(studentID);
        if (studentNode != null)
            {
                StringEventSystem.Global.Send(EventID.StudentUpLevel, studentNode.GetComponentInChildren<Student>().getStudentID());
                UpdateLevel(studentNode); // 升级
            }
    }
    
    // 在 Update 方法之后添加 LateUpdate
    void LateUpdate()
    {
        SortStudentsByYPosition();
    }

    private void SortStudentsByYPosition()
    {
        if (studentsNodes == null || studentsNodes.Count == 0)
            return;

        // 按父节点对活动学生进行分组
        Dictionary<Transform, List<GameObject>> activeStudentsByParent = new Dictionary<Transform, List<GameObject>>();
        
        foreach (GameObject studentNode in studentsNodes)
        {
            // 确保学生节点有效、活动并且有父节点
            if (studentNode == null || !studentNode.activeInHierarchy || studentNode.transform.parent == null)
                continue;

            Transform parent = studentNode.transform.parent;
            if (!activeStudentsByParent.ContainsKey(parent))
            {
                activeStudentsByParent[parent] = new List<GameObject>();
            }
            activeStudentsByParent[parent].Add(studentNode);
        }

        // 对每个父节点下的活动学生列表进行排序和层级调整
        foreach (var kvp in activeStudentsByParent)
        {
            List<GameObject> activeSiblings = kvp.Value;
            
            // 如果该父节点下活动学生数量少于等于1，则无需排序
            if (activeSiblings.Count <= 1) 
                continue;

            // 按Y轴位置升序排序 (Y值小的在前)
            activeSiblings.Sort((s1, s2) => s1.transform.position.y.CompareTo(s2.transform.position.y));

            // 设置同级索引：Y值最小的获得最高的索引，从而显示在最前
            int numActiveSiblings = activeSiblings.Count;
            for (int i = 0; i < numActiveSiblings; i++)
            {
                // activeSiblings[i] 是排序后列表中的第i个学生
                // 它应该获得的新的同级索引是 numActiveSiblings - 1 - i
                activeSiblings[i].transform.SetSiblingIndex(numActiveSiblings - 1 - i);
            }
        }
    }

    //判断学生是否存在
    public bool ContainsStudent(string studentId)
    {
        if (string.IsNullOrEmpty(studentId) || studentsNodes == null)
            return false;
            
        foreach (var student in studentsNodes)
        {
            var studentComp = student.GetComponentInChildren<Student>();
            if (studentComp != null && studentComp.getStudentID() == studentId)
                return true;
        }
        return false;
    }
    
    //根据id找学生
    public GameObject GetStudentById(string studentId)
    {
        if (string.IsNullOrEmpty(studentId) || studentsNodes == null)
            return null;
            
        return studentsNodes.Find(s => 
        {
            var student = s.GetComponentInChildren<Student>();
            return student != null && student.GetComponentInChildren<Student>().getStudentID() == studentId;
        });
    }

    // 新增方法：寻找区域内相对稀疏的位置
    // 参数 numCandidates 控制生成候选点的数量，越多越可能找到更优位置，但计算成本也越高
    private Vector3 FindSparsePosition(Bounds areaBounds, List<GameObject> existingStudents, List<Vector3> currentPendingTargets, int numCandidates = 100)
    {
        // 如果没有现有学生，也没有待处理的目标点，或者候选点数量不合法，直接返回区域内的一个随机点
        if (((existingStudents == null || existingStudents.Count == 0) && 
             (currentPendingTargets == null || currentPendingTargets.Count == 0)) || 
            numCandidates <= 0)
        {
            float randomX = UnityEngine.Random.Range(areaBounds.min.x, areaBounds.max.x);
            float randomY = UnityEngine.Random.Range(areaBounds.min.y, areaBounds.max.y);
            return new Vector3(randomX, randomY, 0f);
        }

        Vector3 bestPosition = Vector3.zero;
        float maxMinDistanceFound = -1f; // 用于记录所有候选点中，其"到最近障碍物（学生或待定目标）的距离"的最大值

        for (int i = 0; i < numCandidates; i++)
        {
            // 在区域内生成一个随机候选位置
            float randomX = UnityEngine.Random.Range(areaBounds.min.x, areaBounds.max.x);
            float randomY = UnityEngine.Random.Range(areaBounds.min.y, areaBounds.max.y);
            Vector3 candidatePosition = new Vector3(randomX, randomY, 0f);

            float currentCandidateMinDistToObstacle = float.MaxValue;
            
            // 计算此候选点到所有现有学生的最小距离
            if (existingStudents != null) 
            {
                foreach (GameObject studentNode in existingStudents)
                {
                    if (studentNode == null || studentNode.transform == null) 
                    {
                        continue;
                    }
                    float dist = Vector3.Distance(candidatePosition, studentNode.transform.position);
                    if (dist < currentCandidateMinDistToObstacle)
                    {
                        currentCandidateMinDistToObstacle = dist;
                    }
                }
            }

            // 计算此候选点到所有待处理目标位置的最小距离
            if (currentPendingTargets != null)
            {
                foreach (Vector3 pendingTarget in currentPendingTargets)
                {
                    float distToPending = Vector3.Distance(candidatePosition, pendingTarget);
                    if (distToPending < currentCandidateMinDistToObstacle)
                    {
                        currentCandidateMinDistToObstacle = distToPending;
                    }
                }
            }

            // 如果这个候选点（相比其他已评估的候选点）离最近的障碍物更远，
            // 或者这是第一个被评估的候选点 (i==0)，则更新 bestPosition。
            if (currentCandidateMinDistToObstacle > maxMinDistanceFound || i == 0)
            {
                maxMinDistanceFound = currentCandidateMinDistToObstacle;
                bestPosition = candidatePosition;
            }
        }
        return bestPosition;
    }


    private void PersonalRight(GameObject studentsNode){
        if (studentsNode == null) return;
        studentsNode.GetComponentInChildren<Student>().setChiTiZhengQue(true);
    }
    private void ClassJiFenFanBei (GameObject studentsNode){
        if (studentsNode == null) return;
        
        int classType = studentsNode.GetComponentInChildren<Student>().getClassType();
        
        foreach (GameObject st in studentsNodes){
            if (st.GetComponentInChildren<Student>().getClassType() == classType){
                st.GetComponentInChildren<Student>().setBeishu();
            }
        }
    }
    private void ClassAllRight (GameObject studentsNode){
        if (studentsNode == null) return;
        if (PlayerPrefs.GetInt(GameMode.correctAnswer) == 0) return;
        int classType = studentsNode.GetComponentInChildren<Student>().getClassType();
        
        foreach (GameObject st in studentsNodes){
            if (st.GetComponentInChildren<Student>().getClassType() == classType){
                if(st.GetComponentInChildren<Student>().getAnswer() !=0){
                    //只要回答问题，就判正确 
                    //TODO 后续看要不要优化为不回答问题也判正确
                    st.GetComponentInChildren<Student>().setAnswer(PlayerPrefs.GetInt(GameMode.correctAnswer));
                }
            }
        }
    }

    private void ClassReduceWrong (GameObject studentsNode){
        if (studentsNode == null) return;
        if (PlayerPrefs.GetInt(GameMode.correctAnswer) == 0) return;
        int classType = studentsNode.GetComponentInChildren<Student>().getClassType();
        
        foreach (GameObject st in studentsNodes){
            if (st.GetComponentInChildren<Student>().getClassType() == classType){
                if(st.GetComponentInChildren<Student>().getAnswer() !=0
                && st.GetComponentInChildren<Student>().getAnswer() != PlayerPrefs.GetInt(GameMode.correctAnswer)){
                    //随机取一个0-1的随机数，如果大于0.5，则赋予正确答案，否则不处理
                    if (UnityEngine.Random.Range(0, 1) > 0.5){
                        st.GetComponentInChildren<Student>().setAnswer(PlayerPrefs.GetInt(GameMode.correctAnswer));
                    }
                }
            }
        }
    }

    // 清除所有学生
    public void ClearAllStudents()
    {
        if (studentsNodes == null) return;

        // 遍历并销毁所有学生对象
        foreach (GameObject student in studentsNodes)
        {
            if (student != null)
            {
                // 如果学生对象还在场景中，则销毁它
                if (Application.isPlaying)
                {
                    Destroy(student);
                }
                else
                {
                    DestroyImmediate(student);
                }
            }
        }

        // 清空列表
        studentsNodes.Clear();
        // 清空待处理的目标位置列表
        pendingTargetPositions.Clear();

        Debug.Log("所有学生已清除");
    }

    // 自动清理学生列表
    private void OnDestroy()
    {
        ClearAllStudents();
    }
}
